package de.karlNet.executor.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.karlNet.executor.io.AppReader;

public class Controller {
	private AppReader appReader = new AppReader();
	

	public String[] getApps() {
		return this.appReader.getApps().toArray(new String[this.appReader.getApps().size()]);
	}



	public void exec(String pgName) throws IOException, InterruptedException {
		pgName = this.appReader.getAppHashMap().get(pgName);
		if (pgName == null) {
			throw new InvalidParameterException("Not such program registered");
		}
		Runtime rt = Runtime.getRuntime();
		// Process pr = rt.exec("cmd /c dir");
		String pgStr = "/usr/bin/open";
		Process pr = rt.exec(new String[] { pgStr, pgName });
		System.exit(0);
		BufferedReader input = new BufferedReader(new InputStreamReader(
				pr.getInputStream()));

		String line = null;

		while ((line = input.readLine()) != null) {
			System.out.println(line);
		}

		int exitVal = pr.waitFor();
	}

	public void scanForApplicatons() {
		this.appReader.readIn();
	}

//	public void scanForApplicatons(String baseDir) {
//		File dir = new File(baseDir);
//		dir.list(new FilenameFilter() {
//			public boolean accept(File dir, String name) {
//				if (name.endsWith(".app")) {
//					int startOfApp = name.indexOf(".app");
//					String newName = name.substring(0, startOfApp);
//					newName.replace(" ", "\\ ");
//					apps.add(newName);
//					hashMap.put(newName, dir.getAbsolutePath() + "/" + name);
//					return true;
//				} else {
//					if (new File(dir.getAbsolutePath() + "/" + name)
//							.isDirectory()) {
//						scanForApplicatons(dir.getAbsolutePath() + "/" + name);
//					}
//				}
//				return false;
//			}
//		});
//
//	}
}
